/**
 * promise
 * @returns
 */
function myPromise(options) {
    //1.创建promise,封装异步任务
    let promise = new Promise(function (resolve, reject) {
        // 2. 封装ajax异步任务
        const xhr = new window.XMLHttpRequest()
        let method = options.method.toUpperCase()
        if (method == 'GET') {
            let params = changeObjParme(options.data)
            xhr.open(method, options.url + '?' + params)
            xhr.send()
        } else if (method == 'POST') {
            xhr.open(method, options.url)
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            let params = changeObjParme(options.data)
            xhr.send(params)
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let data = JSON.parse(xhr.responseText)
                    resolve(data) //resolve成功状态
                } else {
                    reject('请求出错 ' + xhr.status) //reject失败状态
                }
            }
        }
    })
    return promise
}

/**
 * 对象转字符串
 * @param {*} obj 
 * @returns 
 */
function changeObjParme(obj) {
    let arr = [] //[username='admin', password=123]
    for (let key in obj) {
        let params = `${key}=${obj[key]}`
        arr.push(params)
    }
    let line = arr.join('&') //username='admin'&password=123

    return line
}

const formEle = document.querySelector('form')
const usernameInput = document.querySelector('input[name="username"]')
const passwordInput = document.querySelector('input[name="password"]')
const pswMsgEle = document.querySelector('.psw-msg')
const userMsgEle = document.querySelector('.user-msg')



/**
 * 注册
 */
function onLogin() {
    formEle.addEventListener('submit', async function (e) {
        e = e || window.event
        e.preventDefault()

        /*
           用户名非空验证
       */
        function checkUserNameIsNull() {
            let userName = usernameInput.value
            if (userName == '') {
                userMsgEle.innerHTML = '用户名不能为空!'
                return false
            } else {
                userMsgEle.innerHTML = ''
                return true
            }
        }
        checkUserNameIsNull()

        //密码非空验证
        function checkPasswordIsNull() {
            let passWord = passwordInput.value
            if (passWord == '') {
                pswMsgEle.innerHTML = '密码不能为空!'
                return false
            } else {
                pswMsgEle.innerHTML = ''
                return true
            }
        }
        checkPasswordIsNull()




        // 调登录接口
        let data = await myPromise({
            method: 'post',
            url: 'http://api.yuguoxy.com/api/member/login',
            data: {
                username: usernameInput.value,
                password: passwordInput.value,
            },
        })

        if (data.resultCode == -1) {
            alert('会员账号出错')
        }
        if (checkPasswordIsNull() && checkUserNameIsNull() && data.resultCode == 1) {
            // 1. 保存用户信息到localStorage
            let user = data.resultInfo
            localStorage.setItem('USER', JSON.stringify(user))
            // 2. 跳转主界面
            location.href = '../pages/index.html'

        }
    })
}


(function show() {
    //1.设置目的时间
    var oYear = 2022
    var oMonth = 5
    var oDay = 18
    var oHour = 0
    var oMinute = 0
    var oSecond = 0
    var funtureDate = new Date(oYear, oMonth, oDay, oHour, oMinute, oSecond);
    // console.log(dateFormat(funtureDate))
    //2.设置定时器
    setInterval(function () {
        //3.获取现在的时间
        var presentDate = new Date();
        //4.获取时间戳
        var funtureTime = funtureDate.getTime();
        var presenTime = presentDate.getTime();
        //5.获取剩余的时间戳
        var allTime = funtureTime - presenTime;
        //6.把毫秒转换为秒
        var allSecond = parseInt(allTime / 1000);
        //7.获取剩余多少天
        var day = size(parseInt(allSecond / 3600 / 24));
        //8.获取剩余多少小时
        var hour = size(parseInt(allSecond / 3600 % 24));
        //9.获取剩余多少分钟
        var minute = size(parseInt(allSecond / 60 % 60));
        //10.获取剩余多少秒
        var second = size(parseInt(allSecond % 60));
        //11.注入：
        document.getElementById('one').innerHTML = day;
        document.getElementById('two').innerHTML = hour;
        document.getElementById('three').innerHTML = minute;
        document.getElementById('four').innerHTML = second;
    }, 1000);
    //如果数>=10,则在前面补0
    function size(num) {
        return num < 10 & num >= 0 ? '0' + num : num;
    }
})()
//格式化日期格式 2
function dateFormat(data) {
    var date = new Date(data);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
}

/*
    飘落特效
*/
var xh = document.querySelector(".snow");
// 屏幕宽度
var screenWidth = document.body.scrollWidth;
var screenHeight = window.innerHeight;
var setXH = setInterval(function () {
    production();
}, 100);

xh.style.height = screenHeight;

function production() {
    let t1 = document.createElement("div");
    // left 和 top 最大值
    // left 减掉 100 是为了不产生横行的滑动条
    var t1Left = Math.floor(Math.random() * screenWidth) - 100;
    var t1Top = Math.floor(Math.random() * 10);
    t1.style.left = t1Left + "px";
    t1.style.top = t1Top + "px";
    t1.style.display = "inline-block";
    t1.innerText = "$";
    t1.style.color = "white";
    t1.classList.add("xue");

    // 将生成的雪花加入到 div 下面去
    xh.appendChild(t1);

    setInterval(function () {
        t1.remove();
    }, 5000);
}
onLogin()
